package com.shjy.driver.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shjy.driver.R;
import com.shjy.driver.delegate.DetailWebviewDelegate;
import com.shjy.driver.util.Const;

public class DetailActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private TextView mToolbarTitleTextView;
    private ProgressBar mProgressBar;
    private WebView mWebView;

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // layout
        setContentView(R.layout.activity_detail);

        // 初始化 Toolbar
        initToolbar();

        // 初始化 进度条
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

        // 初始化 Webview
        initWebview();

        // 初始化 Handler
        initHandler();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
     * 初始化 Toolbar
     */
    private void initToolbar() {

        // 导航栏标题
        setTitle("");

        // 导航栏设定
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        // 导航栏标题
        mToolbarTitleTextView = (TextView) mToolbar.findViewById(R.id.titleTextView);
        mToolbarTitleTextView.setText("");

        // 设定导航栏返回图标的大小
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        float density = outMetrics.density;
        int right = (int) (20 * density);
        int bottom = right;
        Rect bounds = new Rect(0, 0, right, bottom);

        // 导航栏返回
        TextView backTextView = (TextView) mToolbar.findViewById(R.id.backTextView);
        Drawable[] drawables = backTextView.getCompoundDrawables();
        Drawable drawable = drawables[0];
        drawable.setBounds(bounds);
        backTextView.setCompoundDrawables(drawable, null, null, null);

        backTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = mWebView.getUrl();
                if (url.endsWith("change_price.html") || url.endsWith("select_track.html") || url.endsWith("order_list.html") || url.endsWith("login.html")) {
                    finish();
                }else if (url.indexOf("bid_ok_detail.html")!=-1){
                    Intent intent = new Intent(DetailActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                } else if (url.indexOf("start_bid/start_bid.html")!=-1 || url.indexOf("start_bid/start_bid.html")!=-1){
                    finish();
                }else if (url.indexOf("start_bid/goon_bid")!=-1 ){
                    Intent intent = new Intent(DetailActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                } else if (url.indexOf("bid/ok_bid.html")!=-1){
                    Intent intent = new Intent(DetailActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    } else {
                        finish();
                    }
                }
            }
        });

        setSupportActionBar(mToolbar);
    }

    /**
     * 初始化 Webview
     */
    private void initWebview() {

        // webview
        mWebView = (WebView) findViewById(R.id.webview);

        // 优先使用缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setDomStorageEnabled(true);

        mWebView.setWebChromeClient(new DetailWebChromeClient());
        mWebView.setWebViewClient(new DetailWebviewClient());
        mWebView.addJavascriptInterface(new DetailWebviewDelegate(this, mHandler, mWebView), "delegate");

        mWebView.loadUrl(Const.URL_PREFIX + this.getIntent().getStringExtra("url"));
    }

    private void initHandler() {

        mHandler = new Handler(new Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                return false;
            }
        });
    }

    class DetailWebviewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.indexOf("login.html") != -1) {
                mWebView.stopLoading();
                Intent intent2 = new Intent(DetailActivity.this, LoginActivity.class);
                startActivity(intent2);
            } else {
                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.setProgress(0);
            }
        }
    }

    class DetailWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle(null).setMessage(message).setPositiveButton("确定", null);
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            //return super.onJsConfirm(view, url, message, result);
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle("特别提示")
                    .setMessage(message)
                    .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int which) {
                            result.confirm();
                        }
                    })
                    .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    result.cancel();
                }
            });

            // 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
            builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
                    return true;
                }
            });
            // 禁止响应按back键的事件
            // builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            mToolbarTitleTextView.setText(title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
            if (mProgressBar.getProgress() == mProgressBar.getMax()) {
                mProgressBar.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

}
